package cake.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//mysql��ݿ������
public class MySqlDb {
	//�����ַ�
	private String connStr="jdbc:mysql://localhost/cake?user=root&password=123&useUnicode=true&characterEncoding=UTF8";
	//��ݿ����Ӷ���
	private Connection conn=null;
	private Statement stm=null;
	
	public MySqlDb()
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch(ClassNotFoundException ex)
		{
			ex.printStackTrace();
		}
		
		try {
			//ͨ��mysql��driver������ݿ����Ӷ���
			conn=DriverManager.getConnection(connStr);
			stm=conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	//��ѯ
	public ResultSet query(String sql)
	{
		ResultSet rs=null;
		
		try {
			conn=DriverManager.getConnection(connStr);
			stm=conn.createStatement();
			rs = stm.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	//ִ��sql��������ɾ����޸���
	public int execute(String sql)
	{
		try {
			conn=DriverManager.getConnection(connStr);
			stm=conn.createStatement();
			return stm.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			try {
				this.stm.close();
				this.conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return -1;
	}
	//�ر���ݿ����ӣ��ͷ���Դ
	public void Close()
	{
		try
		{
		if(conn!=null && !conn.isClosed())
		{
			stm.close();
			conn.close();
		}
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
	}
}
